<template>
  <div class="account-permission-page">
    <span class="page-title"><strong>&nbsp;账号权限管理</strong></span>
    <div class="main-card">
      <div class="side-panel">
        <el-button
          class="add-role-btn"
          type="primary"
          icon="el-icon-plus"
          plain
          @click="openAddRoleDrawer"
        >
          <span class="icon-circle-outline">
            <el-icon><Plus /></el-icon>
          </span>
          添加角色
        </el-button>
        <el-menu
          class="role-list"
          :default-active="activeRoleId"
          @select="handleRoleSelect"
        >
          <el-menu-item
            v-for="role in roles"
            :key="role.id"
            :index="String(role.id)"
            class="role-menu-item"
          >
            <span class="role-name">{{ role.roleName }}</span>
            <span class="role-count-badge">{{ role.memberCount }}</span>
            <el-dropdown
              v-if="role.type === '自定义角色'"
              trigger="click"
              class="role-gear-dropdown"
            >
              <el-icon class="role-gear-inline"><Setting /></el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="!cannotEditRoles.includes(role.roleName)"
                    @click="() => openEditRoleDrawer(role)"
                    >编辑角色</el-dropdown-item
                  >
                  <el-dropdown-item @click="() => openViewRoleDialog(role)">查看角色</el-dropdown-item>
                  <el-dropdown-item
                    v-if="!cannotDeleteRoles.includes(role.roleName)"
                    divided
                    @click="() => handleDeleteRole(String(role.id))"
                    >删除角色</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-menu-item>
        </el-menu>
      </div>
      <div class="main-panel">
        <div class="main-header">
          <el-button
            class="add-account-btn"
            type="primary"
            icon="el-icon-plus"
            plain
            @click="addAccountDialogVisible = true"
          >
            <span class="icon-circle-outline">
              <el-icon><Plus /></el-icon>
            </span>
            添加账号
          </el-button>
          <div class="main-header-search">
            <el-input
              class="search-input"
              v-model="keyword"
              placeholder="请输入姓名、手机号进行搜索"
              clearable
              @change="handleSearch"
            >
              <template #append>
                <el-button class="search-btn-circle" @click="handleSearch">
                  <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                    <circle
                      cx="8"
                      cy="8"
                      r="6"
                      stroke="#fff"
                      stroke-width="2"
                      fill="none"
                    />
                    <line
                      x1="13"
                      y1="13"
                      x2="17"
                      y2="17"
                      stroke="#fff"
                      stroke-width="2"
                      stroke-linecap="round"
                    />
                  </svg>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
        <el-table :data="accounts" border style="width: 100%; margin-top: 16px; flex: 1;"
          @sort-change="handleSortChange"
        >
          <el-table-column
            prop="userName"
            label="昵称"
            min-width="110"
            align="center"
          />
          <el-table-column
            prop="mobile"
            label="手机号"
            min-width="140"
            align="center"
          />
          <el-table-column label="角色" min-width="120" align="center">
            <template #default="scope">
              <span v-for="r in scope.row.roleList" :key="r.id">{{
                r.roleName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            min-width="80"
            align="center"
          >
            <template #default="scope">
              <el-tag v-if="scope.row.status === '启用'" type="success"
                >启用</el-tag
              >
              <el-tag v-else type="info">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createdAt"
            label="创建时间"
            min-width="160"
            align="center"
            sortable="custom"
          />
          <el-table-column label="操作" min-width="180" align="center">
            <template #default="scope">
              <el-link
                type="primary"
                style="margin-right: 16px"
                @click="() => handleEditAccountClick(String(scope.row.id))"
                >编辑</el-link
              >
              <el-link
                v-if="scope.row.status === '启用'"
                type="warning"
                style="margin-right: 16px"
                @click="
                  () => showAccountConfirm('disable', String(scope.row.id))
                "
                >禁用</el-link
              >
              <el-link
                v-else
                type="success"
                style="margin-right: 16px"
                @click="
                  () => showAccountConfirm('enable', String(scope.row.id))
                "
                >启用</el-link
              >
              <el-link
                type="danger"
                @click="
                  () => showAccountConfirm('delete', String(scope.row.id))
                "
                >删除</el-link
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-card">
          <div class="pagination-bar">
            <span>共 {{ total }} 条，每页</span>
            <el-select
              v-model="pageSize"
              size="small"
              style="width: 70px; margin: 0 8px"
              disabled
            >
              <el-option
                v-for="size in [10, 20, 50]"
                :key="size"
                :label="size + '条'"
                :value="size"
              />
            </el-select>
            <el-pagination
              background
              layout="prev, pager, next"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
              class="custom-pagination"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="addAccountDialogVisible"
      title="账号添加"
      width="520px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addAccountForm"
        :rules="accountFormRules"
        ref="addAccountFormRef"
        label-width="70px"
        style="margin-top: 10px"
      >
        <el-form-item label="头像">
          <div class="avatar-upload-center">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="() => false"
            :on-change="handleAddAvatarChange"
          >
              <template
              v-if="addAccountForm.avatar && addAccountForm.avatar !== ''"
              >
                <img
              :src="addAccountForm.avatar"
              class="avatar"
              @error="handleImageError"
            />
              </template>
              <template v-else>
                <div class="avatar-upload-placeholder">
                  <i
                    class="el-icon-plus"
                    style="font-size: 28px; color: #bbb"
                  ></i>
                <div class="avatar-upload-text">上传头像</div>
              </div>
              </template>
            </el-upload>
            <div class="avatar-upload-tip">
              最大支持1MB的图片（jpg/png），建议尺寸160x160px
            </div>
          </div>
        </el-form-item>
        <el-form-item label="姓名" prop="userName" required>
          <el-input
            v-model="addAccountForm.userName"
            placeholder="请输入姓名"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" required>
          <el-input
            v-model="addAccountForm.mobile"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleID" required>
          <el-select v-model="addAccountForm.roleID" style="width: 100%">
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addAccountDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddAccount">添加</el-button>
      </template>
    </el-dialog>
    <div v-if="editAccountDialogVisible" class="dialog-flex-container">
      <div class="custom-dialog-box">
        <div class="drawer-header" style="position: relative">
          <span class="drawer-title">账号编辑</span>
          <el-button
            class="custom-dialog-close-btn"
            circle
            @click="editAccountDialogVisible = false"
    >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <el-form
          :model="editAccountForm"
          :rules="accountFormRules"
          ref="editAccountFormRef"
          label-width="70px"
          style="margin-top: 10px; padding: 0 24px"
        >
        <el-form-item label="头像">
            <div class="avatar-upload-center">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="() => false"
            :on-change="handleEditAvatarChange"
          >
                <template
              v-if="editAccountForm.avatar && editAccountForm.avatar !== ''"
                >
                  <img
              :src="editAccountForm.avatar"
              class="avatar"
              @error="handleImageError"
            />
                </template>
                <template v-else>
                  <div class="avatar-upload-placeholder">
                    <i
                      class="el-icon-plus"
                      style="font-size: 28px; color: #bbb"
                    ></i>
                <div class="avatar-upload-text">上传头像</div>
              </div>
                </template>
            </el-upload>
              <div class="avatar-upload-tip">
                最大支持1MB的图片（jpg/png），建议尺寸160x160px
              </div>
            </div>
        </el-form-item>
        <el-form-item label="姓名" prop="userName" required>
            <el-input
              v-model="editAccountForm.userName"
              placeholder="请输入姓名"
              maxlength="20"
            />
        </el-form-item>
        <el-form-item label="角色" prop="roleID" required>
          <el-select v-model="editAccountForm.roleID" style="width: 100%">
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
          <el-form-item label="手机号" prop="mobile" required>
            <el-input
              v-model="editAccountForm.mobile"
              placeholder="请输入手机号"
              maxlength="11"
              disabled
              style="width: 220px"
            />
            <el-link
              type="primary"
              style="margin-left: 8px; font-size: 14px"
              @click="openChangePhoneDialog"
              >修改手机号</el-link
            >
        </el-form-item>
      </el-form>
        <div
          style="
            display: flex;
            justify-content: flex-end;
            padding: 0 24px 24px 24px;
          "
        >
        <el-button @click="editAccountDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditAccount">保存</el-button>
        </div>
      </div>
      <div
        v-if="changePhoneDialogVisible"
        class="custom-dialog-box change-phone-drawer"
      >
        <div class="drawer-header" style="position: relative">
          <span class="drawer-title">账号编辑</span>
          <el-button
            class="custom-dialog-close-btn"
            circle
            @click="changePhoneDialogVisible = false"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <el-form
          :model="changePhoneForm"
          label-width="70px"
          style="margin-top: 10px; padding: 0 24px"
        >
          <el-form-item label="头像">
            <div class="avatar-upload-center">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="() => false"
                :on-change="handleEditAvatarChange"
              >
                <template
                  v-if="changePhoneForm.avatar && changePhoneForm.avatar !== ''"
                >
                  <img
                    :src="changePhoneForm.avatar"
                    class="avatar"
                    @error="handleImageError"
                  />
      </template>
                <template v-else>
                  <div class="avatar-upload-placeholder">
                    <i
                      class="el-icon-plus"
                      style="font-size: 28px; color: #bbb"
                    ></i>
                    <div class="avatar-upload-text">上传头像</div>
                  </div>
                </template>
              </el-upload>
              <div class="avatar-upload-tip">
                最大支持1MB的图片（jpg/png），建议尺寸160x160px
              </div>
            </div>
          </el-form-item>
          <el-form-item label="姓名" required>
            <el-input
              v-model="changePhoneForm.userName"
              placeholder="请输入姓名"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item label="角色" required>
            <el-select v-model="changePhoneForm.roleID" style="width: 100%">
              <el-option
                v-for="role in roleOptions"
                :key="role.value"
                :label="role.label"
                :value="role.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="原手机号">
            <el-input
              v-model="changePhoneForm.oldPhone"
              placeholder="请输入原手机号"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="验证码">
            <el-input
              v-model="changePhoneForm.oldCode"
              placeholder="请输入验证码"
              maxlength="6"
              style="width: 180px"
            />
            <el-button style="margin-left: 8px">获取验证码</el-button>
          </el-form-item>
          <el-form-item label="新手机号">
            <el-input
              v-model="changePhoneForm.newPhone"
              placeholder="请输入新手机号"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="验证码">
            <el-input
              v-model="changePhoneForm.newCode"
              placeholder="请输入验证码"
              maxlength="6"
              style="width: 180px"
            />
            <el-button style="margin-left: 8px">获取验证码</el-button>
          </el-form-item>
        </el-form>
        <div
          style="
            display: flex;
            justify-content: flex-end;
            padding: 0 24px 24px 24px;
          "
        >
          <el-button @click="changePhoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleChangePhone">保存</el-button>
        </div>
      </div>
    </div>
    <el-drawer
      v-model="roleDrawerVisible"
      size="720px"
      direction="rtl"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <template #header>
        <div class="drawer-header">
          <span class="drawer-title">{{
            roleDrawerMode === "add" ? "角色添加" : "角色编辑"
          }}</span>
          <div class="drawer-actions">
            <el-button @click="roleDrawerVisible = false">取消</el-button>
            <el-button
              type="primary"
              class="deep-blue-btn"
              @click="
                roleDrawerMode === 'add' ? handleAddRole() : handleEditRole()"
            >{{ roleDrawerMode === "add" ? "添加" : "保存" }}</el-button>
          </div>
        </div>
      </template>
      <el-form label-width="90px" style="margin-top: -2.5rem; padding-right: 1.5rem">
        <el-form-item label="角色名" required style="margin-bottom: 1rem">
          <el-input
            v-model="roleForm.roleName"
            :value="roleForm.roleName || ''"
            placeholder="请输入角色名"
            maxlength="20"
          />
        </el-form-item>
        <div style="width: 100%">
          <!-- 人工审核认证卡片 -->
          <div class="perm-card-form perm-card-group" style="margin-bottom: 1.5rem">
            <div class="perm-section-title">人工审核认证</div>
            <div class="perm-card-inner">
              <div class="perm-card-row">
                <el-checkbox-group
                  v-model="permissionForm.audit"
                  class="perm-checkbox-group"
                >
                <el-checkbox
                    v-for="item in permissionGroups[0].children"
                    :key="item.code"
                    :label="item.code"
                  >
                    {{ item.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
          <!-- 意见反馈卡片 -->
          <div class="perm-card-form perm-card-group" style="margin-bottom: 1.5rem">
            <div class="perm-section-title">意见反馈</div>
            <div class="perm-card-inner">
              <div class="perm-card-row">
                <el-checkbox-group
                  v-model="permissionForm.feedback"
                  class="perm-checkbox-group"
                >
                  <el-checkbox
                    v-for="item in permissionGroups[1].children"
                    :key="item.code"
                    :label="item.code"
                  >
                    {{ item.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
          <!-- 产品套餐大卡片 -->
          <div class="perm-card-form perm-card-group">
            <div class="perm-section-title">产品套餐</div>
            <div class="perm-card-inner">
              <!-- 产品管理 -->
              <div>
                <div class="perm-card-title">产品管理</div>
                <div class="perm-row-single">
                  <el-checkbox
                    :indeterminate="isIndeterminate('product')"
                    :checked="isAllChecked('product')"
                    @change="toggleAll('product', $event)"
                    >全选</el-checkbox
                  >
                </div>
                <div class="perm-row-group">
                  <el-checkbox-group
                    v-model="permissionForm.product"
                    class="perm-checkbox-group"
                  >
                    <el-checkbox
                      v-for="item in permissionGroups[2].children"
                      :key="item.code"
                      :label="item.code"
                    >
                      {{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
              <!-- 分割线 -->
              <div class="perm-divider"></div>
              <!-- 套餐管理 -->
              <div>
                <div class="perm-card-title">套餐管理</div>
                <div class="perm-row-single">
                  <el-checkbox
                    :indeterminate="isIndeterminate('package')"
                    :checked="isAllChecked('package')"
                    @change="toggleAll('package', $event)"
                    >全选</el-checkbox
                  >
                </div>
                <div class="perm-row-group">
                  <el-checkbox-group
                    v-model="permissionForm.package"
                    class="perm-checkbox-group"
                  >
                    <el-checkbox
                      v-for="item in permissionGroups[3].children"
                      :key="item.code"
                      :label="item.code"
                    >
                      {{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </el-drawer>
    <el-dialog
      v-model="accountConfirmDialog.visible"
      :title="
        accountConfirmDialog.type === 'enable'
          ? '账号启用确认'
          : accountConfirmDialog.type === 'disable'
          ? '账号禁用确认'
          : '账号删除确认'
      "
      width="480px"
      :close-on-click-modal="false"
    >
      <div style="margin: 18px 0 32px 0; font-size: 16px; color: #333">
        <template v-if="accountConfirmDialog.type === 'enable'">
          是否确认启用该账号？启用后该账号可再次登录使用易企盘点管理平台。
        </template>
        <template v-else-if="accountConfirmDialog.type === 'disable'">
          是否确认禁用该账号？禁用后该账号将无法登录易企盘点管理平台。
        </template>
        <template v-else>
          是否确认删除该账号？删除后该账号将无法登录易企盘点管理平台。
        </template>
      </div>
      <template #footer>
        <el-button @click="accountConfirmDialog.visible = false"
          >取消</el-button
        >
        <el-button
          v-if="accountConfirmDialog.type === 'enable'"
          type="primary"
          @click="handleConfirmEnable"
          >确认</el-button
        >
        <el-button
          v-if="accountConfirmDialog.type === 'disable'"
          type="danger"
          @click="handleConfirmDisable"
          >确认禁用</el-button
        >
        <el-button
          v-if="accountConfirmDialog.type === 'delete'"
          type="danger"
          @click="handleConfirmDelete"
          >确认删除</el-button
        >
      </template>
    </el-dialog>
    <el-drawer
      v-model="roleDetailDrawerVisible"
      title=""
      size="720px"
      direction="rtl"
      :close-on-click-modal="false"
      :with-header="false"
    >
      <div class="role-detail-custom-header" style="display: flex; align-items: center; justify-content: space-between; padding: 1.25rem 0.5rem 0.5rem 0;">
        <div class="role-detail-title" style="margin: 0; padding: 0; margin-left: 0;">角色详情</div>
        <el-button circle @click="roleDetailDrawerVisible = false" style="background: none; border: none; box-shadow: none;">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <div class="role-detail-divider" style="margin-bottom: 0.5rem;"></div>
      <div class="role-detail-name-row" style="margin-bottom: 0.5rem;">角色名称：{{ roleDetailForm.roleName }}</div>
      <el-form label-width="90px" style="margin-top: 0; padding-right: 24px;">
        <el-form-item style="margin-bottom: 0;">
          <div class="perm-group-list perm-group-list-narrow" style="margin-top: 0;">
            <!-- 人工审核认证卡片 -->
            <div class="perm-card-form perm-card-group role-detail-wide-card" style="margin-bottom: 1.5rem;">
              <div class="perm-section-title">人工审核认证</div>
              <div class="perm-card-inner">
              <div class="perm-card-row">
                  <el-checkbox-group
                    v-model="roleDetailPermissionForm.audit"
                    class="perm-checkbox-group"
                    disabled
                  >
                <el-checkbox
                      v-for="item in permissionGroups[0].children"
                      :key="item.code"
                      :label="item.code"
                  disabled
                    >
                    {{ item.label }}
                  </el-checkbox>
                </el-checkbox-group>
                </div>
              </div>
            </div>
            <!-- 意见反馈卡片 -->
            <div class="perm-card-form perm-card-group role-detail-wide-card" style="margin-bottom: 1.5rem;">
              <div class="perm-section-title">意见反馈</div>
              <div class="perm-card-inner">
                <div class="perm-card-row">
                  <el-checkbox-group
                    v-model="roleDetailPermissionForm.feedback"
                    class="perm-checkbox-group"
                    disabled
                  >
                    <el-checkbox
                      v-for="item in permissionGroups[1].children"
                      :key="item.code"
                      :label="item.code"
                      disabled
                    >
                      {{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
            <!-- 产品套餐大卡片 -->
            <div class="perm-card-form perm-card-group role-detail-wide-card">
              <div class="perm-section-title">产品套餐</div>
              <div class="perm-card-inner">
                <!-- 产品管理 -->
                <div>
                  <div class="perm-card-title">产品管理</div>
                  <div class="perm-row-single">
                    <el-checkbox
                      :indeterminate="isIndeterminateDetail('product')"
                      :checked="isAllCheckedDetail('product')"
                      disabled
                      >全选</el-checkbox
                    >
                  </div>
                  <div class="perm-row-group">
                    <el-checkbox-group
                      v-model="roleDetailPermissionForm.product"
                      class="perm-checkbox-group"
                      disabled
                    >
                      <el-checkbox
                        v-for="item in permissionGroups[2].children"
                        :key="item.code"
                        :label="item.code"
                        disabled
                      >
                        {{ item.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
                <!-- 分割线 -->
                <div class="perm-divider"></div>
                <!-- 套餐管理 -->
                <div>
                  <div class="perm-card-title">套餐管理</div>
                  <div class="perm-row-single">
                    <el-checkbox
                      :indeterminate="isIndeterminateDetail('package')"
                      :checked="isAllCheckedDetail('package')"
                      disabled
                      >全选</el-checkbox
                    >
                  </div>
                  <div class="perm-row-group">
                    <el-checkbox-group
                      v-model="roleDetailPermissionForm.package"
                      class="perm-checkbox-group"
                      disabled
                    >
                      <el-checkbox
                        v-for="item in permissionGroups[3].children"
                        :key="item.code"
                        :label="item.code"
                        disabled
                      >
                        {{ item.label }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Setting, Plus, Close } from "@element-plus/icons-vue";
import {
  getRoleList,
  addRole,
  editRole,
  deleteRole,
  getAdminListByPage,
  addAdminUser,
  editAdminUser,
  deleteUser,
  changeUserStatus,
  getRoleDropdownList,
  viewAdminUser,
  getUserDropdownList,
  viewRole,
} from "@/api/AccountPermissionManagement";
import { useLoginEmpStore } from "@/stores/loginEmp";
import type { RoleListItem, AdminUserListItem } from "@/api/model/model";
import type { UploadFile } from "element-plus";
import { uploadFile } from '@/api/common';

const addAccountFormRef = ref();
const editAccountFormRef = ref();

// 角色相关
const roles = ref<RoleListItem[]>([]);
const activeRoleId = ref<string>("");
const roleOptions = ref<{ label: string; value: string }[]>([]);

// 账号相关
const accounts = ref<AdminUserListItem[]>([]);
const pageSize = ref(10);
const currentPage = ref(1);
const total = ref(0);
const keyword = ref("");

// 弹窗控制
const addAccountDialogVisible = ref(false);
const editAccountDialogVisible = ref(false);
const roleDrawerVisible = ref(false);
const roleDrawerMode = ref<"add" | "edit">("add");
const roleForm = ref({
  id: "",
  roleName: "",
  permissionList: "",
});

// 新增：账号操作确认弹窗
const accountConfirmDialog = ref({
  visible: false,
  type: "", // 'enable' | 'disable' | 'delete'
  accountId: "",
});

// 表单数据
const addAccountForm = ref({
  userName: "",
  mobile: "",
  roleID: "",
  avatar: "",
});
const editAccountForm = ref({
  id: "",
  userName: "",
  mobile: "",
  roleID: "",
  avatar: "",
  oldMobile: "",
  oldMobileCode: "",
  newMobile: "",
  newMobileCode: "",
});

// 表单校验规则
const accountFormRules = {
  userName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度为2-20位", trigger: "blur" },
  ],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1\d{10}$/, message: "手机号格式不正确", trigger: "blur" },
  ],
  roleID: [{ required: true, message: "请选择角色", trigger: "change" }],
};

// 表单重置方法
const resetAddAccountForm = () => {
  addAccountForm.value = {
    userName: "",
    mobile: "",
    roleID: "",
    avatar: "",
  };
  // 清除表单校验状态
  nextTick(() => {
    addAccountFormRef.value?.clearValidate();
  });
};

const resetEditAccountForm = () => {
  editAccountForm.value = {
    id: "",
    userName: "",
    mobile: "",
    roleID: "",
    avatar: "",
    oldMobile: "",
    oldMobileCode: "",
    newMobile: "",
    newMobileCode: "",
  };
  // 清除表单校验状态
  nextTick(() => {
    editAccountFormRef.value?.clearValidate();
  });
};

const resetChangePhoneForm = () => {
  changePhoneForm.value = {
    avatar: "",
    userName: "",
    roleID: "",
    oldPhone: "",
    oldCode: "",
    newPhone: "",
    newCode: "",
  };
};

// 权限分组配置
const permissionGroups = [
  {
    key: "audit",
    label: "人工审核认证",
    children: [{ code: "0202", label: "审核处理" }],
  },
  {
    key: "feedback",
    label: "意见反馈",
    children: [{ code: "0402", label: "意见回复" }],
  },
  {
    key: "product",
    label: "产品管理",
    children: [
      { code: "0501", label: "产品查看" },
      { code: "0502", label: "产品添加" },
      { code: "0503", label: "产品编辑" },
      { code: "0504", label: "产品删除" },
    ],
  },
  {
    key: "package",
    label: "套餐管理",
    children: [
      { code: "0601", label: "套餐查看" },
      { code: "0602", label: "套餐添加" },
      { code: "0603", label: "套餐编辑" },
      { code: "0604", label: "套餐删除" },
    ],
  },
];

// 权限表单结构
const permissionForm = ref<Record<string, string[]>>({
  audit: [],
  feedback: [],
  product: [],
  package: [],
});

// 全选/半选逻辑
function isAllChecked(groupKey: string) {
  return (
    permissionForm.value[groupKey].length ===
    permissionGroups.find((g) => g.key === groupKey)?.children.length
  );
}
function isIndeterminate(groupKey: string) {
  const total =
    permissionGroups.find((g) => g.key === groupKey)?.children.length || 0;
  const checked = permissionForm.value[groupKey].length;
  return checked > 0 && checked < total;
}
function toggleAll(groupKey: string, checked: boolean) {
  const group = permissionGroups.find((g) => g.key === groupKey);
  if (!group) return;
  permissionForm.value[groupKey] = checked
    ? group.children.map((c) => c.code)
    : [];
}

// 提交前组装权限
function getPermissionList() {
  // 扁平化所有选中的code
  return Object.values(permissionForm.value).flat();
}

// 获取角色列表
async function fetchRoles() {
  try {
  const res = await getRoleList();
  // 先拿到真实角色
  const realRoles = res.data.data || [];
  // 统计所有账号数
  const allCount = total.value || 0;
  // 插入全部角色
  roles.value = [
      { id: 0, roleName: "全部角色", type: "全部", memberCount: allCount },
      ...realRoles,
  ];
  roleOptions.value = roles.value.map((r) => ({
    label: r.roleName,
    value: String(r.id),
  }));
  // 默认选中全部角色
    activeRoleId.value = "";
    await fetchAccounts();
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败，请刷新页面重试');
  }
}

// 获取角色下拉
async function fetchRoleDropdown() {
  try {
  const res = await getRoleDropdownList();
  roleOptions.value = (res.data.data || []).map((r) => ({
    label: r.roleName,
    value: String(r.id),
  }));
  } catch (error) {
    console.error('获取角色下拉列表失败:', error);
    ElMessage.error('获取角色列表失败');
  }
}

// 获取账号列表
async function fetchAccounts() {
  try {
  const params: Record<string, any> = {
      page: String(currentPage.value || ""),
      pageSize: String(pageSize.value || ""),
  };
  if (activeRoleId.value) params.roleID = activeRoleId.value;
  if (keyword.value) params.keyword = keyword.value;
    if (orderBy.value) params.orderBy = orderBy.value;
    console.log('请求参数:', params); // 调试用
  const res = await getAdminListByPage(params);
  accounts.value = res.data.data.pageData.list || [];
  total.value = res.data.data.pageData.total || 0;
  } catch (error) {
    console.error('获取账号列表失败:', error);
    ElMessage.error('获取账号列表失败，请重试');
  }
}

function handleSortChange({ prop, order }: { prop: string; order: string }) {
  console.log('排序字段:', prop, '顺序:', order); // 调试用
  let realOrder = '';
  if (order === 'ascending') realOrder = 'ascend';
  else if (order === 'descending') realOrder = 'descend';
  else realOrder = order;
  if (realOrder) {
    orderBy.value = JSON.stringify({ field: prop, order: realOrder });
  } else {
    orderBy.value = "";
  }
  currentPage.value = 1;
  fetchAccounts();
}

// 获取用户下拉
const userDropdownOptions = ref<{ label: string; value: string }[]>([]);
async function fetchUserDropdown() {
  try {
  const res = await getUserDropdownList();
  userDropdownOptions.value = (res.data.data || []).map((u) => ({
    label: u.userName,
    value: String(u.id),
  }));
  } catch (error) {
    console.error('获取用户下拉列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
}

onMounted(() => {
  fetchRoles();
  fetchRoleDropdown();
  fetchUserDropdown();
  // 默认选中全部角色
  activeRoleId.value = "";
});

function handleRoleSelect(roleId: string) {
  activeRoleId.value = roleId;
  currentPage.value = 1;
  fetchAccounts();
}

function handlePageChange(page: number) {
  currentPage.value = page;
  fetchAccounts();
}
function handleSearch() {
  currentPage.value = 1;
  fetchAccounts();
}

// 角色操作
function openAddRoleDrawer() {
  roleDrawerMode.value = "add";
  roleForm.value = { id: "", roleName: "", permissionList: "" };
  Object.keys(permissionForm.value).forEach(
    (k) => (permissionForm.value[k] = [])
  );
  roleDrawerVisible.value = true;
}
function openEditRoleDrawer(role: any) {
  roleDrawerMode.value = "edit";
  roleForm.value = {
    id: String(role.id || ""),
    roleName: role.roleName,
    permissionList: role.permissionList || "[]",
  };
  fillPermissionForm(JSON.parse(roleForm.value.permissionList));
  roleDrawerVisible.value = true;
}
async function handleAddRole() {
  roleForm.value.permissionList = JSON.stringify(getPermissionList());
  try {
    const res = await addRole(roleForm.value);
    if (res.data.code === "100") {
      ElMessage.success("角色添加成功");
    roleDrawerVisible.value = false;
    fetchRoles();
    } else {
      ElMessage.error(res.data.message || "角色添加失败");
    }
  } catch (e) {
    ElMessage.error("角色添加失败");
  }
}
async function handleEditRole() {
  roleForm.value.permissionList = JSON.stringify(getPermissionList());
  try {
    const res = await editRole(roleForm.value);
    if (res.data.code === "100") {
      ElMessage.success("角色编辑保存成功");
      roleDrawerVisible.value = false;
      fetchRoles();
    } else {
      ElMessage.error("角色编辑保存失败，请重新尝试");
    }
  } catch (e) {
    ElMessage.error("角色编辑保存失败，请重新尝试");
  }
}
async function handleDeleteRole(roleId: string | undefined) {
  try {
    await ElMessageBox.confirm(
      "是否确认删除该角色？禁用后该角色下的账号都将转至默认角色下。",
      "角色删除确认",
      {
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger",
      }
    );
    // 调用删除接口
    const res = await deleteRole({ id: String(roleId || "") });
    if (res.data.code === "100") {
      ElMessage.success("角色删除成功");
      fetchRoles();
    } else {
      ElMessage.error("角色删除失败，请重新尝试");
    }
  } catch (e) {
    // 用户点了取消，不需要提示
    if (e !== "cancel") {
      ElMessage.error("角色删除失败，请重新尝试");
    }
  }
}

// 账号操作
async function handleAddAccount() {
  const formRef = addAccountFormRef.value;
  if (!formRef) return;
  await formRef.validate(async (valid: boolean) => {
    if (!valid) return;
    try {
      await addAdminUser({ ...addAccountForm.value });
      addAccountDialogVisible.value = false;
      activeRoleId.value = "";
      currentPage.value = 1;
      await fetchAccounts();
      ElMessage.success("账号添加成功");
    } catch (e) {
      ElMessage.error({ message: "账号添加失败，请重新尝试", showClose: true });
    }
  });
}
async function handleEditAccount() {
  const formRef = editAccountFormRef.value;
  if (!formRef) return;
  await formRef.validate(async (valid: boolean) => {
    if (!valid) return;
    try {
      await editAdminUser({ ...editAccountForm.value });
      editAccountDialogVisible.value = false;
      await fetchAccounts();
      ElMessage.success("账号编辑成功");
    } catch (e) {
      ElMessage.error({ message: "账号编辑失败，请重新尝试", showClose: true });
    }
  });
}
async function handleDeleteAccount(accountId: string | undefined) {
  console.log("点击了删除账号", accountId);
  try {
    await ElMessageBox.confirm("确定要删除该账号吗？", "提示", {
      type: "warning",
    });
    console.log("准备发删除账号请求");
    await deleteUser({ id: String(accountId || "") });
    console.log("删除账号请求已发出");
    fetchAccounts();
  } catch (e) {
    console.error("账号删除异常", e);
    ElMessage.error({ message: "账号删除失败，请重新尝试", showClose: true });
  }
}
async function handleChangeStatus(
  accountId: string | undefined,
  status: "启用" | "停用"
) {
  console.log("点击了账号状态变更", accountId, status);
  try {
    console.log("准备发账号状态变更请求");
    await changeUserStatus({ id: String(accountId || ""), status });
    console.log("账号状态变更请求已发出");
    fetchAccounts();
  } catch (e) {
    console.error("账号状态变更异常", e);
  }
}

function handleAddAvatarChange(file: UploadFile) {
  console.log('开始上传头像，文件信息:', file);
  if (file.raw) {
    console.log('文件原始数据:', file.raw);
    console.log('文件大小:', file.raw.size, '字节');
    console.log('文件类型:', file.raw.type);

    uploadFile({
      uploadFile: file.raw
    }).then((res) => {
      console.log('完整的上传响应:', res);
      console.log('res的类型:', typeof res);
      console.log('res的键:', Object.keys(res));
      console.log('res.data:', res.data);
      console.log('res.data的类型:', typeof res.data);
      console.log('res.data的键:', Object.keys(res.data || {}));
      console.log('响应数据结构:', {
        hasData: !!res.data,
        dataType: typeof res.data,
        code: res.data?.code,
        message: res.data?.message,
        hasFileData: !!res.data?.data?.file,
        fileUrl: res.data?.data?.file?.url
      });

      if (res.data.code === "100") {
        const avatarUrl = res.data.data.file.url || "";
        addAccountForm.value.avatar = avatarUrl;
        console.log(
          "上传后addAccountForm.avatar:",
          addAccountForm.value.avatar
        );
        ElMessage.success("头像上传成功");
      } else {
        console.error('上传失败，响应码:', res.data.code, '消息:', res.data.message);
        ElMessage.error(res.data.message || "头像上传失败");
      }
    }).catch((error) => {
      console.error("头像上传失败:", error);
      console.error("错误详情:", error.message);
      ElMessage.error("头像上传失败，请重试");
    });
  } else {
    console.error('文件原始数据为空');
    ElMessage.error("文件数据异常，请重试");
  }
}

function handleEditAvatarChange(file: UploadFile) {
  if (file.raw) {
    uploadFile({
      uploadFile: file.raw
    }).then((res) => {
      if (res.data.code === "100") {
        const avatarUrl = res.data.data.file.url || "";
        editAccountForm.value.avatar = avatarUrl;
        console.log(
          "上传后editAccountForm.avatar:",
          editAccountForm.value.avatar
        );
        ElMessage.success("头像上传成功");
      } else {
        ElMessage.error(res.data.message || "头像上传失败");
      }
    }).catch((error) => {
      console.error("头像上传失败:", error);
      ElMessage.error("头像上传失败，请重试");
    });
  }
}

function isSystemRole(type: string) {
  return type === "系统角色";
}

async function handleEditAccountClick(accountId: string | undefined) {
  console.log("开始获取账号详情:", accountId);
  const res = await viewAdminUser({ id: String(accountId || "") });
  const data = res.data.data;
  console.log("获取到的账号数据:", data);
  editAccountForm.value.id = String(data.id || "");
  editAccountForm.value.userName = data.userName;
  editAccountForm.value.mobile = data.mobile;
  editAccountForm.value.roleID = String(data.roleList?.[0]?.id || "");
  editAccountForm.value.avatar = data.avatar || "";
  console.log("设置编辑表单数据:", editAccountForm.value);
  editAccountDialogVisible.value = true;
}

// 编辑时权限回显
function fillPermissionForm(permissionList: string[]) {
  // 先清空
  Object.keys(permissionForm.value).forEach(
    (k) => (permissionForm.value[k] = [])
  );
  for (const group of permissionGroups) {
    permissionForm.value[group.key] = group.children
      .filter((c) => permissionList.includes(c.code))
      .map((c) => c.code);
  }
}

// 账号操作
function showAccountConfirm(
  type: "enable" | "disable" | "delete",
  accountId: string
) {
  accountConfirmDialog.value.type = type;
  accountConfirmDialog.value.accountId = accountId;
  accountConfirmDialog.value.visible = true;
}

async function handleConfirmEnable() {
  console.log("点击了账号启用确认");
  try {
    console.log("准备发账号启用请求");
    await changeUserStatus({
      id: String(accountConfirmDialog.value.accountId || ""),
      status: "启用",
    });
    console.log("账号启用请求已发出");
    ElMessage.success({ message: "账号启用成功", showClose: true });
    accountConfirmDialog.value.visible = false;
    fetchAccounts();
  } catch (e) {
    console.error("账号启用异常", e);
    ElMessage.error({ message: "账号启用失败，请重新尝试", showClose: true });
  }
}
async function handleConfirmDisable() {
  console.log("点击了账号禁用确认");
  try {
    console.log("准备发账号禁用请求");
    await changeUserStatus({
      id: String(accountConfirmDialog.value.accountId || ""),
      status: "停用",
    });
    console.log("账号禁用请求已发出");
    ElMessage.success({ message: "账号禁用成功", showClose: true });
    accountConfirmDialog.value.visible = false;
    fetchAccounts();
  } catch (e) {
    console.error("账号禁用异常", e);
    ElMessage.error({ message: "账号禁用失败，请重新尝试", showClose: true });
  }
}
async function handleConfirmDelete() {
  console.log("点击了账号删除确认");
  try {
    console.log("准备发账号删除请求");
    await deleteUser({
      id: String(accountConfirmDialog.value.accountId || ""),
    });
    console.log("账号删除请求已发出");
    ElMessage.success({ message: "账号删除成功", showClose: true });
    accountConfirmDialog.value.visible = false;
    fetchAccounts();
  } catch (e) {
    console.error("账号删除异常", e);
    ElMessage.error({ message: "账号删除失败，请重新尝试", showClose: true });
  }
}

// 图片加载错误处理
function handleImageError(event: Event) {
  console.warn("图片加载失败:", event);
  const target = event.target as HTMLImageElement;
  if (target) {
    target.style.display = "none";
  }
}

const cannotDeleteRoles = [
  "超级管理员",
  "默认角色",
  "客服经理",
  "主办会计",
  "出纳",
  "销售经理",
];
const cannotEditRoles = ["超级管理员"];

async function openViewRoleDialog(role: any) {
  // 调用接口获取角色详情
  const res = await viewRole({ id: String(role.id) });
  if (res.data.code === "100" && res.data.data) {
    roleDetailForm.value.roleName = res.data.data.roleName;
    // 注意接口返回 permissionCode
    fillRoleDetailPermissionForm(res.data.data.permissionCode || []);
  roleDetailDrawerVisible.value = true;
  } else {
    ElMessage.error(res.data.message || "获取角色详情失败");
  }
}

function fillRoleDetailPermissionForm(permissionList: string[]) {
  Object.keys(roleDetailPermissionForm.value).forEach(
    (k) => (roleDetailPermissionForm.value[k] = [])
  );
  for (const group of permissionGroups) {
    roleDetailPermissionForm.value[group.key] = group.children
      .filter((c) => permissionList.includes(c.code))
      .map((c) => c.code);
  }
}

function isAllCheckedDetail(groupKey: string) {
  return (
    roleDetailPermissionForm.value[groupKey].length ===
    permissionGroups.find((g) => g.key === groupKey)?.children.length
  );
}

function isIndeterminateDetail(groupKey: string) {
  const total =
    permissionGroups.find((g) => g.key === groupKey)?.children.length || 0;
  const checked = roleDetailPermissionForm.value[groupKey].length;
  return checked > 0 && checked < total;
}

const roleDetailDrawerVisible = ref(false);
const roleDetailForm = ref({
  roleName: "",
  permissionList: "",
});
const roleDetailPermissionForm = ref<Record<string, string[]>>({
  audit: [],
  feedback: [],
  product: [],
  package: [],
});

const changePhoneDialogVisible = ref(false);
const changePhoneForm = ref({
  avatar: "",
  userName: "",
  roleID: "",
  oldPhone: "",
  oldCode: "",
  newPhone: "",
  newCode: "",
});

watch(editAccountDialogVisible, (val) => {
  if (!val) {
    changePhoneDialogVisible.value = false;
  }
});

function openChangePhoneDialog() {
  // 深拷贝左侧表单数据到右侧
  changePhoneForm.value.avatar = editAccountForm.value.avatar;
  changePhoneForm.value.userName = editAccountForm.value.userName;
  changePhoneForm.value.roleID = editAccountForm.value.roleID;
  changePhoneForm.value.oldPhone = editAccountForm.value.mobile;
  changePhoneForm.value.oldCode = "";
  changePhoneForm.value.newPhone = "";
  changePhoneForm.value.newCode = "";
  changePhoneDialogVisible.value = true;
  nextTick(() => {
    // 可选：聚焦第一个输入框
  });
}

function handleChangePhone() {
  // 这里写你的axios请求逻辑
  // 假设成功
  try {
    // await axios.post('/api/change-phone', changePhoneForm.value)
    ElMessage.success("手机号修改成功");
    changePhoneDialogVisible.value = false;
  } catch (e) {
    ElMessage.error("手机号修改失败");
  }
}

defineExpose({
  cannotDeleteRoles,
  cannotEditRoles,
  openViewRoleDialog,
});

const orderBy = ref("");
</script>

<style scoped>
.account-permission-page {
  background: #f5f6fa;
  min-height: 100vh;
  margin: 32px 0 0 0;
  padding: 32px 24px 0 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
}
.page-title {
  font-size: 20px;
  margin-bottom: 24px;
  color: #222;
  text-align: left;
  display: block;
  width: 100%;
  margin-left: 0;
  margin-top: 0;
  padding-top: 0;
  position: relative;
  top: -32px;
}
.main-card {
  width: 90%;
  margin: 0 auto 32px auto;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
  display: flex;
  padding: 2.5rem 3rem 2rem 3rem;
  min-height: 37.5rem;
  box-sizing: border-box;
  position: relative;
  top: -32px;
  transition: all 0.3s ease;
}
.side-panel {
  width: 15rem;
  min-width: 15rem;
  border-right: 0.0625rem solid #f0f0f0;
  padding: 2rem 2rem 0 1rem;
  border-radius: 0.875rem 0 0 0.875rem;
  background: #fff;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  box-sizing: border-box;
  overflow-x: hidden !important;
}
.add-role-btn {
  width: 11.25rem;
  margin-bottom: 1.125rem;
  margin-left: 1.25rem;
  align-self: flex-start;
}
.add-role-btn,
.add-account-btn {
  background: #f7f8fa !important;
  border: none !important;
  color: #333 !important;
  font-weight: 500;
  box-shadow: none !important;
}
.add-role-btn:hover,
.add-account-btn:hover {
  background: #f0f1f3 !important;
  color: #222 !important;
}
.role-list {
  width: 100%;
  border: none;
  background: transparent;
  margin-top: 0;
  flex-grow: 1;
  overflow-x: hidden !important;
  white-space: nowrap !important;
}
.role-menu-item {
  display: flex !important;
  justify-content: space-between;
  align-items: center;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}
.role-name {
  flex: 1 1 auto;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
}
.role-count-badge {
  min-width: 1.375rem;
  text-align: right;
  margin-left: 0.5rem;
  margin-right: 0;
}
.role-gear-dropdown {
  margin-left: 0.5rem;
  display: flex;
  align-items: center;
}
.role-gear-inline {
  font-size: 1.125rem;
  color: #bbb;
  cursor: pointer;
}
.role-gear-inline:hover {
  color: #333;
}
.main-panel {
  flex: 1;
  min-width: 0;
  padding: 2rem 2rem 2rem 2rem;
  background: #fff;
  border-radius: 0 0.875rem 0.875rem 0;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
.main-header {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
  justify-content: space-between;
}
.main-header-search {
  position: relative;
  flex-shrink: 0;
}
.search-input {
  width: 20rem;
  min-width: 20rem;
}
.search-input .el-input__inner {
  background: #fff;
  border: 0.0625rem solid #e5e6eb;
  color: #222;
  box-shadow: none;
}
.search-input :deep(.el-input-group__append) {
  padding: 0;
  background: transparent;
  border: none;
}
.search-btn-circle {
  width: 2.25rem;
  height: 2.25rem;
  background: #1765ff !important;
  border: none !important;
  border-radius: 0 0.25rem 0.25rem 0 !important;
  color: #fff !important;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 !important;
  box-shadow: none;
}
.search-btn-circle:hover {
  background: #0958d9 !important;
}
.search-btn-circle svg {
  display: block;
  color: #fff;
}
.pagination-card {
  background: #fff;
  border-radius: 0.75rem;
  box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.04);
  padding: 1.125rem 2rem 1.125rem 1.5rem;
  position: absolute;
  right: 2rem;
  bottom: 0rem;
  margin: 0;
  z-index: 10;
  border-top: 2px solid #fff;
}
.pagination-bar {
  display: flex;
  align-items: center;
  font-size: 0.9375rem;
  color: #888;
  gap: 0.25rem;
}
.custom-pagination {
  margin-left: 0.5rem;
}
.el-pagination {
  background: transparent;
  box-shadow: none;
  font-size: 1rem;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.el-pagination .el-pager li {
  background: #fff;
  border-radius: 0.5rem;
  color: #222;
  min-width: 2.25rem;
  height: 2.25rem;
  line-height: 2.25rem;
  margin: 0 0.25rem;
  font-size: 1rem;
  border: 0.09375rem solid #e5e6eb;
  transition: all 0.2s;
}
.el-pagination .el-pager li.is-active {
  background: #222;
  color: #fff;
  border-color: #222;
}
.el-pagination .el-pager li:hover:not(.is-active) {
  background: #f5f6fa;
  color: #222;
  border-color: #bcbcbc;
}
.el-pagination .el-select .el-input__inner {
  background: #fafbfc;
  color: #bbb;
  border-radius: 0.5rem;
  font-size: 0.9375rem;
  height: 2.25rem;
  line-height: 2.25rem;
}
.el-pagination .el-select .el-input__inner[disabled] {
  background: #f5f6fa;
  color: #ccc;
  cursor: not-allowed;
}
.avatar-uploader {
  display: inline-block;
  vertical-align: top;
}
.avatar-upload-block {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.avatar-uploader {
  background: #fff;
  border-radius: 0.5rem;
}
.avatar-upload-placeholder {
  width: 5rem;
  height: 5rem;
  border: 0.09375rem dashed #d9d9d9;
  border-radius: 0.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 1rem;
  background: #fff;
  cursor: pointer;
  transition: background 0.2s;
}
.avatar-upload-placeholder:hover {
  background: #f5f6fa;
}
.avatar-upload-text {
  font-size: 0.875rem;
  color: #888;
  margin-top: 0.125rem;
}
.avatar-upload-tip {
  color: #bcbcbc;
  font-size: 0.875rem;
  margin-top: 0.5rem;
  margin-left: 0;
  text-align: left;
}
.avatar {
  width: 5rem;
  height: 5rem;
  border-radius: 0.5rem;
  object-fit: cover;
  border: 0.09375rem solid #e6e6e6;
}
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 0 !important;
  padding: 0 !important;
  margin: 0 !important;
  border-bottom: none !important;
}
.drawer-title {
  font-size: 1.25rem;
  font-weight: bold;
  color: #222;
}
.drawer-actions {
  display: flex;
  flex-direction: row;
  gap: 0.75rem;
}
.perm-group-list {
  display: flex;
  flex-direction: column;
  gap: 1.125rem;
  margin-top: 0.5rem;
}
.perm-card {
  width: 100%;
  background: #fff;
  border-radius: 0.625rem;
  box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.04);
  margin-bottom: 1.5rem;
  border: none;
}
.perm-card-title {
  font-weight: bold;
  font-size: 1rem;
  color: #222;
  margin-bottom: 0.625rem;
  text-align: left;
}
.perm-card-row {
  display: flex;
  align-items: center;
  gap: 1.125rem;
}
.perm-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem 1.5rem;
  margin-bottom: 0;
}
.perm-checkbox-group .el-checkbox {
  margin-right: 0;
}
.pagination-card.fixed-bottom-right {
  position: relative;
  background: #fff;
  box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.04);
  border-radius: 0.75rem;
  padding: 1.125rem 2rem 1.125rem 1.5rem;
  margin: 1rem 0 1.5rem 0;
}
.icon-circle-outline {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 1.25rem;
  height: 1.25rem;
  border-radius: 50%;
  background: #fff;
  border: 0.09375rem solid #222;
  color: #222;
  margin-right: 0.375rem;
  font-size: 0.875rem;
}
.avatar-upload-tip-inline {
  color: #bcbcbc;
  font-size: 0.875rem;
  margin-left: 1rem;
  white-space: nowrap;
}
.change-phone-drawer {
  width: 32.5rem;
  min-height: 32.5rem;
  max-height: 90vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background: #fff;
  box-shadow: 0 0.125rem 0.75rem rgba(0, 0, 0, 0.12);
  border-radius: 0.625rem;
}
.change-phone-drawer .drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.5rem 1.5rem 0 1.5rem;
  font-size: 1.25rem;
  font-weight: bold;
  color: #222;
}
.change-phone-drawer .drawer-title {
  font-size: 1.25rem;
  font-weight: bold;
  color: #222;
}
.dialog-flex-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 4000;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: rgba(0, 0, 0, 0.08);
  gap: 2rem;
  padding-top: 3.75rem;
}
.custom-dialog-box {
  background: #fff;
  border-radius: 0.625rem;
  box-shadow: 0 0.125rem 0.75rem rgba(0, 0, 0, 0.12);
  min-width: 30rem;
  max-width: 37.5rem;
  margin: 0 2rem;
  padding: 2rem 2.25rem 1.5rem 2.25rem;
  position: relative;
  display: flex;
  flex-direction: column;
}
.custom-dialog-close {
  font-size: 1.25rem;
  cursor: pointer;
}
.custom-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}
.avatar-upload-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 0.5rem;
  margin-top: 0.5rem;
}
.avatar-upload-tip {
  color: #bcbcbc;
  font-size: 0.8125rem;
  margin-top: 0.5rem;
  text-align: center;
}
.role-detail-title {
  font-weight: bold;
  font-size: 1.25rem;
  color: #222;
  margin-bottom: 0.5rem;
  margin-top: 0;
  text-align: left;
  padding-top: 0;
}
.role-detail-divider {
  width: 100%;
  height: 0.09375rem;
  background: #f0f0f0;
  margin-bottom: 0.5rem;
}
.role-detail-name-row {
  font-size: 1rem;
  color: #222;
  font-weight: 400;
  margin-bottom: 0.5rem;
  text-align: left;
}
.perm-group-list-narrow {
  width: 100%;
  max-width: 56.25rem;
  margin: 0 auto;
  margin-top: 0 !important;
}
.perm-card {
  width: 100%;
  background: #fff;
  border-radius: 0.625rem;
  box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.04);
  margin-bottom: 1.5rem;
  border: none;
}
.perm-card-row-split {
  margin-bottom: 0;
  margin-top: 0;
}
.perm-card-form {
  background: #fff;
  border-radius: 0.5rem;
  box-shadow: 0 0.0625rem 0.5rem rgba(0, 0, 0, 0.06);
  padding: 1.125rem 1.5rem;
  margin-bottom: 0;
}
.perm-card-group {
  padding: 0;
  overflow: hidden;
}
.perm-section-title {
  background: #f5f6fa;
  color: #222;
  font-weight: bold;
  font-size: 1rem;
  border-radius: 0.5rem 0.5rem 0 0;
  padding: 0.75rem 1.5rem;
  margin-bottom: 0;
}
.perm-card-inner {
  padding: 1.125rem 1.5rem;
}
.perm-divider {
  height: 0.0625rem;
  background: #f0f0f0;
  margin: 1.125rem 0;
}
.el-form {
  margin-top: 0 !important;
}
.el-form-item {
  margin-bottom: 1.125rem;
}
.perm-row-single {
  margin-bottom: 0.5rem;
}
.perm-row-group {
  display: flex;
  gap: 1.5rem;
  margin-bottom: 0.5rem;
}
.custom-dialog-close-btn {
  background: #f5f6fa !important;
  color: #888 !important;
  border: none !important;
  box-shadow: none !important;
  position: absolute;
  top: 1rem;
  right: 1rem;
  z-index: 10;
}
.custom-dialog-close-btn:hover {
  background: #eee !important;
  color: #222 !important;
}
.drawer-header {
  position: relative;
}
/* 操作列按钮统一深蓝色 */
.el-table .el-link.el-link--primary,
.el-table .el-link.el-link--warning,
.el-table .el-link.el-link--danger {
  color: #1765ff !important;
  border: none !important;
  background: none !important;
}
.el-table .el-link.el-link--primary:hover,
.el-table .el-link.el-link--warning:hover,
.el-table .el-link.el-link--danger:hover {
  color: #0958d9 !important;
}
.deep-blue-btn {
  background: #1765ff !important;
  border-color: #1765ff !important;
  color: #fff !important;
}
.deep-blue-btn:hover,
.deep-blue-btn:focus {
  background: #0958d9 !important;
  border-color: #0958d9 !important;
  color: #fff !important;
}
:deep(.el-drawer__body) {
  padding-top: 0 !important;
}
.role-detail-wide-card {
  width: 100% !important;
  max-width: none !important;
  margin-left: -24px !important;
  margin-right: -24px !important;
  box-sizing: border-box !important;
}
/* 彻底去掉表格所有横线、竖线、补丁线、底线 */
:deep(.el-table th),
:deep(.el-table td) {
  border: none !important;
}

:deep(.el-table),
:deep(.el-table__inner-wrapper) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
}

/* 只去掉线，不隐藏结构 */
:deep(.el-table__inner-wrapper::after),
:deep(.el-table::after),
:deep(.el-table--border::after) {
  border: none !important;
  background: none !important;
  box-shadow: none !important;
  height: 0 !important;
  width: 0 !important;
}

/* 左侧补丁线变白色 */
:deep(.el-table__border-left-patch) {
  background: #fff !important;
  border-left: 1px solid #fff !important;
  width: 0 !important;
}

/* 查看角色时禁用复选框的样式覆盖 */
.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #409eff !important;
  border-color: #409eff !important;
}

.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-checked .el-checkbox__inner::after {
  border-color: #fff !important;
}

.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #409eff !important;
  border-color: #409eff !important;
}

.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-indeterminate .el-checkbox__inner::after {
  background-color: #fff !important;
}

/* 更强的样式覆盖，确保禁用状态下显示选中效果 */
:deep(.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff !important;
  border-color: #409eff !important;
}

:deep(.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-checked .el-checkbox__inner::after) {
  border-color: #fff !important;
}

:deep(.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #409eff !important;
  border-color: #409eff !important;
}

:deep(.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-indeterminate .el-checkbox__inner::after) {
  background-color: #fff !important;
}

/* 确保勾号显示 */
:deep(.role-detail-wide-card .el-checkbox.is-disabled .el-checkbox__input.is-checked .el-checkbox__inner::after) {
  transform: rotate(45deg) scaleY(1) !important;
  border: 2px solid #fff !important;
  border-left: 0 !important;
  border-top: 0 !important;
  left: 6px !important;
  top: 2px !important;
  width: 4px !important;
  height: 8px !important;
}

/* 表头矩形浅灰色 */
:deep(.el-table__header-wrapper thead tr) {
  background: #f5f6fa !important;
  border-radius: 8px !important;
}
:deep(.el-table__header-wrapper th) {
  background: transparent !important;
  border-radius: 0 !important;
  border: none !important;
  padding-top: 16px !important;
  padding-bottom: 16px !important;
}

/* 去掉表格所有竖线 */
:deep(.el-table th),
:deep(.el-table td) {
  border-right: none !important;
}

/* 去掉表格外边框 */
:deep(.el-table) {
  border: none !important;
  margin-bottom: 2.5rem !important;
}

:deep(.el-table__inner-wrapper),
:deep(.el-table),
:deep(.el-table--border),
:deep(.el-table__inner-wrapper::after),
:deep(.el-table::after),
:deep(.el-table--border::after),
:deep(.el-table__border-left-patch) {
  border-left: 1px solid #fff !important;
  background: #fff !important;
  box-shadow: none !important;
}
</style>

<style>
.el-message-box {
  top: 20vh !important;
}
</style>

@media (max-width: 87.5rem) {
  .main-card {
    max-width: 95vw;
    margin: 0 1rem 2rem 1rem;
  }

  .side-panel {
    width: 12rem;
    min-width: 12rem;
    padding: 1.5rem 1.5rem 0 1.5rem;
  }

  .main-panel {
    padding: 1.5rem 1.5rem 0 1.5rem;
  }

  .search-input {
    width: 16rem;
    min-width: 16rem;
  }
}

@media (max-width: 62.5rem) {
  .main-card {
    flex-direction: column;
    max-width: 100vw;
    margin: 0 0.5rem 2rem 0.5rem;
    padding: 1.5rem 1.5rem 1.5rem 1.5rem;
  }

  .side-panel {
    width: 100%;
    min-width: auto;
    border-right: none;
    border-bottom: 0.0625rem solid #f0f0f0;
    border-radius: 0.875rem 0.875rem 0 0;
    padding: 1.5rem 1.5rem 1.5rem 1.5rem;
    margin-bottom: 1.5rem;
  }

  .main-panel {
    padding: 0;
    border-radius: 0 0 0.875rem 0.875rem;
  }

  .main-header {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }

  .main-header-search {
    align-self: flex-end;
  }

  .search-input {
    width: 100%;
    min-width: auto;
  }
}

/* 新增：统一卡片响应式设计 */
@media (max-width: 1400px) {
  .main-card {
    width: 90%;
    max-width: none;
  }
}

@media (max-width: 1200px) {
  .main-card {
    width: 95%;
  }
}

@media (max-width: 1000px) {
  .main-card {
    width: 98%;
    padding: 2rem 2rem 1.5rem 2rem;
  }
}

@media (max-width: 768px) {
  .main-card {
    width: 100%;
    margin: 0 0.5rem 1rem 0.5rem;
    padding: 1rem;
    top: -16px;
  }

  .side-panel {
    padding: 1rem;
  }

  .main-panel {
    padding: 1rem;
  }

  .search-input {
    width: 100%;
  }

  .add-role-btn,
  .add-account-btn {
    width: 100%;
    margin-left: 0;
  }

  .page-title {
    top: -16px;
  }
}

@media (max-width: 480px) {
  .account-permission-page {
    padding: 1rem 0.5rem 0 0.5rem;
  }

  .main-card {
    margin: 0 0.25rem 1rem 0.25rem;
    padding: 0.75rem;
    top: -8px;
  }

  .side-panel {
    padding: 0.75rem;
  }

  .main-panel {
    padding: 0.75rem;
  }

  .page-title {
    font-size: 1.125rem;
    margin-bottom: 1rem;
    top: -8px;
  }
}
